from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.urls import reverse

from .libs import *
from .viewlib import *
from .models import *


# Create your views here.
def index(request):
    return render(request,"netdisk/index.html")

def signup(request):
    context = {}
    if request.method == "POST":
        uname = request.POST.get("uname")
        upasswd1 = request.POST.get("upasswd1")
        upasswd2 = request.POST.get("upasswd2")
        ugender = request.POST.get("ugender")
        utel = request.POST.get("utel")
        uemail = request.POST.get("uemail")
        ujieshao = request.POST.get("ujieshao")
        input_rs,reason = checkup_signup(uname=uname,upasswd1=upasswd1,upasswd2=upasswd2,utel=utel,uemail=uemail)
        if input_rs:
            if User.objects.filter(uname=uname).count() == 0:
                upasswd1 = sha1sum(upasswd1)
                user = User(uname=uname,upasswd=upasswd1,ugender=ugender,utel=utel,uemail=uemail,
                            ujieshao=ujieshao)
                user.save()
                request.session['user'] = uname
                request.session.set_expiry(0)#关闭浏览器清除登录session
                return redirect(reverse("netdisk:index"))
            else:
                context={"reason":"账户名已存在"}
        else:
            context={"reason":reason}
    return render(request,"netdisk/signup.html",context)

def login(request):
    context = {}
    uname = request.session.get("user","")
    if uname:
        return redirect(reverse("netdisk:index"))
    if request.method == "POST":#截获post请求
        ucaptcha = request.POST.get("captcha")
        session_captcha = request.session.get("captcha")
        if session_captcha is not None and ucaptcha == session_captcha:#判断验证码
            uname = request.POST.get("uname")
            upasswd = request.POST.get("upasswd")
            ulasttime = request.POST.get("ulasttime")
            upasswd = sha1sum(upasswd)
            if User.objects.filter(uname=uname,upasswd=upasswd).count()==1:#比对用户名密码，登录成功
                #添加cookie和session
                request.session["user"] = uname
                request.session.set_expiry(0)#关闭浏览器清除session
                return redirect(reverse("netdisk:index"))
            else:
                context={"reason":"用户名或者密码不一致！"}
        else:
            context = {"reason":"验证码不匹配！"}

    return render(request,"netdisk/login.html",context)

def logout(request):
    del request.session["user"]
    return redirect(reverse('netdisk:index'))

def gen_captcha(request):
    image,rand_str = gen_captchalib()
    # 存入session，用于做进一步验证
    request.session['captcha'] = rand_str
    return HttpResponse(image, 'image/png')